<?php

namespace addons\facrm\controller\facrm\product;

use addons\facrm\library\BackendApi;

use app\common\model\Category as CategoryModel;
use fast\Tree;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 商品分类
 *
 * @icon fa fa-circle-o
 */
class Type extends BackendApi {

    /**
     * Type模型对象
     * @var \app\admin\model\ykjp\product\Type
     */
    protected $model = null;
    protected $distinguish = true;

    public function _initialize() {
        parent::_initialize();
        $this->model = new \app\admin\model\facrm\product\Type;

        $tree = Tree::instance();
        $tree->init(collection($this->model->order('weigh desc,id desc')->select())->toArray(), 'pid');
        $this->categorylist = $tree->getTreeList($tree->getTreeArray(0), 'name');
        $categorydata = [0 => ['type' => 'all', 'name' => __('None')]];
        foreach ($this->categorylist as $k => $v) {
            $categorydata[$v['id']] = $v;
        }
        $this->view->assign("parentList", $categorydata);
        $this->request->filter(['strip_tags']);
    }

    /**
     * 商品分类列表
     */
    public function index() {
        $search = $this->request->request("search");
        $type = $this->request->request("type");

        //构造父类select列表选项数据

        $list = $this->categorylist;

        $result = array("rows" => $list);

        return $this->success('', $result);
    }

    /**
     * 编辑分类
     */
    public function edit()
    {
        $id = $this->request->request('id', '', 'intval');
        if (!$id) {
            $this->error(__('No Results were found'));
        }
        $row = $this->model->get($id);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("");
            if ($params) {
                if ($params['pid'] != $row['pid']) {
                    $childrenIds = Tree::instance()->init(collection($this->model::select())->toArray())->getChildrenIds($row['id'], true);
                    if (in_array($params['pid'], $childrenIds)) {
                        $this->error(__('父组别不能是它的子组别或它自己'));
                    }
                }

                try {
                    $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    $row->validateFailException(true)->validate($name . '.edit');
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->success('', $row);
    }



    /**
     * 添加分类
     * @ApiMethod (POST)
     * @ApiBody ("其它参数参考电脑版,去掉row,取里面的")
     */
    public function add()
    {

        $params = $this->request->post();
        if ($params) {
            $result = false;
            Db::startTrans();
            try {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $result = $this->model->validateFailException(true)->validate($name . '.add')->allowField(true)->isUpdate(false)->save($params);
                Db::commit();
            } catch (ValidateException $e) {

                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success();
            } else {
                $this->error(__('No rows were inserted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', ''));
    }
}
